package Controller;

import Model.Sport;
import Model.SportBean;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/CaipanLookSport")
public class CaipanLookSport extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Context context = null;
        HttpSession session = request.getSession();
        try {
            context = new InitialContext();
            Context contextNeeded = (Context) context.lookup("java:comp/env");
            DataSource ds = (DataSource) contextNeeded.lookup("wq");// 获得连接池。
            Connection conn = null;
            ResultSet rs;
            String sql;
            PreparedStatement pstmt;
            conn = ds.getConnection();//获得数据源
            sql = "select * from sport";
            pstmt =  conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            SportBean sb = (SportBean) session.getAttribute("sportBean");
            if(sb==null){
                sb = new SportBean();
            }
            SportBean temp = new SportBean();
            Sport d;
            while (rs.next()){
                d = new Sport();
                d.setSno(rs.getString(1));
                d.setSname(rs.getString(2));
                d.setRule(rs.getString(3));
                d.setStime(rs.getString(4));
                d.setSplace(rs.getString(5));
                d.setSnum(rs.getInt(6));
                temp.add(d);
            }
            sb.setSports(temp.getSports());
            session.setAttribute("sportBean",sb);
            conn.close();
            response.sendRedirect("caipan/look_sport.jsp");
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("加载不成功");
        }
    }
}
